/**
 * Created by rAGEnchi.Giab on 11/2/16.
 */

//评论框键盘收起
function packupKeyboard() {
    $(".moreDiv").remove();
    $("#task-detail-footer").css("bottom",'0vh');
    $(".task-comment-box-real").blur();
}

    //获取页面间的url的参数
(function ($) {
    $(function(){
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        };

        //页面跳转返回type
        /*
        * detailBack 0返回我的任务列表
        *            2返回动态列表
        *            5返回项目详情
        * */
        var projectBackType = $.getUrlParam('projectComment');
        var taskBackType = $.getUrlParam('taskListBack'); //返回任务列表对应的3个页面（我关注的，我发起的，我负责的）
        if (taskBackType == undefined){
            taskBackType = 0;
        }

        var backType = ''; //backType = 1 时表示返回原生应用，其余返回H5页面
        var userToken = $.getUrlParam('token');
        if (userToken == undefined){
            backType = $.getUrlParam('detailBack');
        }
        else {
            backType = 1;
        }
        var taskDetailUserId = '';
        var taskDetailToken = '';
        var taskDetailImtoken = '';
        var taskDetailQyxBindId = '';
        var taskDetailGroupId = '';

        var deleteItemId = 0;

        if (backType == 1){
            taskDetailUserId = $.getUrlParam('userId');
            taskDetailToken = $.getUrlParam('token');
            taskDetailImtoken = $.getUrlParam('imToken');
            taskDetailQyxBindId = $.getUrlParam('qyxBindId');
            taskDetailGroupId = $.getUrlParam('teamId');
        }
        else {
            taskDetailUserId = user_id;
            taskDetailToken = token;
            taskDetailImtoken = imToken;
            taskDetailQyxBindId = qyxBindId;
            taskDetailGroupId = group_id;
        }
    //全局的任务标识
    var project_task_id = $.getUrlParam('id');
        var taskDetailUserName = "";
    //全局的任务对象
    var task;
    //全局的是否关注任务
    var isFollow;
        //全局任务所属项目ID
        var task_project_id = '';
        //选中的负责人
        var selectPrincipal = '';

    //评论附件
    var comment_file = '';

        //最后一条评论ID
        var lastCommentId = 0;
    //修改后的时间
    var changeTimestamp = '';

        //下载附件参数
        var file_data_down = '';
        var file_name_down = '';

    var userArray = [];
    var commentUserArray = [];

        var quitShare;
        quitShare                    = document.createElement('iframe');
        quitShare.style.display      = 'none';
        document.documentElement.appendChild(quitShare);
    //第一次获取详情
    projectTaskDetail();

        $(document).on('focus', '.task-comment-box-real', function () {
            var fileHeight = $(".taskFileLi").length * 6.5;
            if (fileHeight < 40) {
                var scrollVh = (40 - fileHeight) + 'vh';
                $("#task-detail-footer").css("bottom",scrollVh);
            }
        });

        $(document).on("click","#navigation-left",function(){
            if (backType == 2){
                window.location.href = "../../index.html?htmlType=2";
            }
            else if (backType == 0){
                window.location.href = "../../index.html?htmlType=0&taskListBack="+taskBackType;
            }
            else if (backType == 1){
                //返回原生应用
                quitShare.src = "/quitShare_goBack";
            }else {
                if (projectBackType != undefined){
                    window.location.href = "../project/projectDetail.html?project_id="+task_project_id+"&tabbarCount=1&projectCommentBack=1";
                }else {
                    window.location.href = "../project/projectDetail.html?project_id="+task_project_id+"&tabbarCount=1";
                }
            }
        });

        $(document).on("click","#addMemberNavigation-left",function(){
            //返回
            $("#addMemberDiv").hide();
            $(".taskDetail-container").show();
            $(".member-li").remove();
            selectPrincipal = '';
        });

    $(document).on("click","#more",function(){
        $(".call_back").show();
    });

    $(document).on("click","#cancelMore",function(){
        $(".call_back").hide();
    });

        //点击下载文件
        var downloadFile;
        downloadFile = document.createElement('iframe');
        downloadFile.style.display = 'none';
        document.documentElement.appendChild(downloadFile);
        $(document).on("click",".call_back_down",function(){
            $(".call_back_down").hide();
        });

        $(document).on("click","#cancel_down",function(){
            $(".call_back_down").hide();
        });

        $(document).on("click","#sure_down",function(){
            $(".call_back_down").hide();
            downloadFile.src = "/downloadFile_downThisFile?url=http://"+file_data_down+"&fileName="+file_name_down+"";
        });

    $(document).on("click","#deleteTask",function(){
        $(".call_back").hide();
        if (taskDetailUserId == task.create_id){
            $(".title_big").text("确认删除此任务?");
            $(".call_back_dele").show();
        }
        else {
            $(".project-alert").text("您无权限删除任务").show().fadeOut(2000);
        }
    });

        $(document).on("click","#dele_cancel",function(){
            $(".call_back_dele").hide();
        });

        $(document).on("click","#dele_sure",function(){
            $(".call_back_dele").hide();
            var title = $(".title_big").text();
            if (title == "确认删除此检查项?") {
                deleteTaskItem(deleteItemId);
            }
            else {
                deleteProjectTask(project_task_id,taskDetailUserId);
            }
        });

    $(document).on("click",".call_back_project",function(){
        $(".call_back_project").hide();
        $('.title_up_project').remove();
    });

    $(document).on("click","#moveTask",function(){
        if (taskDetailUserId == task.create_id){
            projectLists(taskDetailUserId);
        }
        else {
            $(".project-alert").text("您无权限移动任务").show().fadeOut(2000);
            $(".call_back").hide();
        }
    });

        $(document).on("click","#shareToTalk",function(){
            var attId           ="";
            var team            =taskDetailGroupId;
            var content         ="任务分享";
            var title           ="";
            var applicationId   =task.project_task_id;
            var applicationType =4;
            var attSize         ="";
            var hyperlink       ="/task/html/task/taskDetail.html?id=" + task.project_task_id + "";

            shareContent(attId,team,content,title,applicationId,applicationType,attSize,hyperlink);
        });

    $(document).on("click",".task-bottom-comment-box-icon",function(){
        packupKeyboard();
        $("#upload_file").click();
    });

    $(document).on('change','#upload_file',function(){
        var formdata=new FormData($("#form_file")[0]);
        var file = this.files[0];
        if (file != undefined){
            var file_size_k = file.size;
            var file_size;
            if(file_size_k<1000){
                file_size = Math.round(file_size_k) + "B";
            }else if(file_size_k<1000000){
                file_size = Math.round(file_size_k/1024) + "KB";
            }else{
                file_size = Math.round(file_size_k/1024/1024) + "MB";
            }


            var file_name = file.name;

            if (checkFileType(file_name) == true){
                formdata.append("type","1");
                formdata.append("file_size", file_size);

                $.ajax({
                    type : 'POST',
                    url : apiurl+'/global/singleUpload',
                    data: formdata,
                    cache : false,
                    processData : false,
                    contentType : false,
                    mimeType:"multipart/form-data",
                    beforeSend:function(){
                        $(".change-p").text("正在上传附件");
                        $(".change-alert").show();
                    },
                    complete:function(d){
                        $(".change-alert").hide();
                    },
                    success : function(d){
                        var comData = d;
                        if (d.code == undefined) {
                            comData = JSON.parse(d);
                        }
                        if (comData.code == 0){
                            var data = JSON.parse(d).data;
                            var fileId = data.file_id;
                            var fileName = data.file_name;
                            var arr = fileName.split(".");
                            var type = '';
                            var imgUrl = '';
                            if (arr[arr.length - 1] == "jpg" || arr[arr.length - 1] == "png" || arr[arr.length - 1] == "jpeg" || arr[arr.length - 1] == "gif" || arr[arr.length - 1] == "bmp" || arr[arr.length - 1] == "psd" || arr[arr.length - 1] == "dwg" || arr[arr.length - 1] == "ico") {
                                type = "taskPicImg";
                                imgUrl = '../../images/task/pic.png';
                            }
                            else {
                                type = "taskFileImg";
                                imgUrl = '../../images/project/word.png';
                            }

                            var html = '<li class="taskFileLi" fileId ='+fileId+'>'+
                                '<img class="'+type+'" src="'+imgUrl+'"/>'+
                                '<p class="taskFileName">'+fileName+'</p>'+
                                '<img class="deleteTaskFileImg" src="../../images/task/crossRed.png"/>'+
                                '<div style="clear: both"></div>' +
                                '</li>'
                            $(".taskFileUl").append(html);


                            var fileCount = 0;
                            $(".taskFileLi").each(function(index){
                                fileCount += 1;
                            });

                            marBottom = (8.33 + 6.5 * fileCount) + 'vh';
                            $(".content-div").css("margin-bottom", marBottom);

                            var h = $(document).height()-$(window).height();
                            $(document).scrollTop(h);

                        }
                        else {
                            $(".project-alert").text("Error").show().fadeOut(2000);
                        }
                    },
                    error:function(d){
                        $(".project-alert").text("网络不给力").show().fadeOut(2000);
                    }

                })
            }else {
                $(".call_back_success").text("不支持该文件类型!").fadeIn();
                setTimeout(function(){
                    $(".call_back_success").fadeOut(1000);
                },1000);
            }
        }
        var fileInput = $('#upload_file');
        fileInput.replaceWith(fileInput.val('').clone(true));
    });

    //删除附件
    $(document).on("click",".deleteTaskFileImg",function(){
        $(this).parent().remove();

        var fileCount = 0;
        $(".taskFileLi").each(function(index){
            fileCount += 1;
        });

        var marBottom = (8.33 + 6.5 * fileCount) + 'vh';
        $(".content-div").css("margin-bottom", marBottom);
    });

    var stop=false;//触发开关，防止多次调用事件
    $(document).ready(function(){

        $(window).scroll(function() {
            //当内容滚动到底部时加载新的内容 100当距离最底部100个像素时开始加载.
            if ($(this).scrollTop() + $(document).height() +100>= $(document).height()) {
                if (stop == true) {
                    stop = false;
                    taskCommentList(true);
                }
            }
        });

    });

    //评论发送
    $(document).on("click",".task-send-btn",function(){
        packupKeyboard();
        var fileIdArray = [];
        if($(".taskFileLi").length>0){
            $(".taskFileLi").each(function(index){
                fileIdArray[index] = $(this).attr("fileId");
            });
            comment_file = fileIdArray.join(",");
        }else{
            comment_file = "";
        }
        var body = $(".task-comment-box-real").html();
        if (body.length > 0 || comment_file.length > 0){
            var data = {
                project_task_id:task.project_task_id,
                project_id:task.project_id,
                user_id:taskDetailUserId,
                comment_body:body,
                comment_file:comment_file,
                token:taskDetailToken,
                imtoken:taskDetailImtoken,
                qyxBindId:taskDetailQyxBindId,
                title:task.project_task_name+"有新的评论"
            };
            $.ajax({
                url:  apiurl + "/projects/task/comment",
                type: "POST",
                dataType: 'json',
                data:data,
                //contentType: "charset=utf-8",
                beforeSend:function(){
                    $(".change-p").text("正在发送评论");
                    $(".change-alert").show();
                },
                complete:function(d){
                    $(".change-alert").hide();
                },
                success: function (d) {
                    if (d.msg == 202){
                        $(".token_iframe").show();
                    }
                    else {
                        var data = d;
                        if (d.code == undefined) {
                            data = JSON.parse(d);
                        }
                        if (data.code == 0) {
                            var comment = JSON.parse(d).data;
                            var createName = '';
                            var avatar = '';
                            var qyxBindId = '';
                            for (key in commentUserArray) {
                                if (commentUserArray[key].id == comment.user_id) {
                                    createName = commentUserArray[key].name;
                                    avatar = commentUserArray[key].avatar;
                                    qyxBindId = commentUserArray[key].qyxBindId;
                                }
                            }
                            var img_url;
                            //if (avatar == "") {
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(createName) + "</div>"
                            //} else {
                            if (avatar.length > 0){
                                var src = avatar_getUrl(taskDetailUserId, taskDetailToken, avatar);
                                img_url += "<img src='" + src + "' class='user_pic' hidden>";
                            }
                            $(".task-comment-box-real").text('');
                            initDate(new Date(comment.timestamp));
                            var html = "";
                            var htmlLi = "";

                            var array = comment.comment_body.split('\n');
                            var html_single = "";
                            for(var key in array){
                                html_single += "<div class='real_content'>"+array[key]+"</div>";
                            }


                            if (comment.comment_file.length > 0) {

                                html = '<div class="comment" project_task_comment_id="' + comment.project_task_comment_id + '">' +
                                    '<div class="detailCommentDiv">' +
                                        //'<img class="avatar" src="'+avatar+'" />' +
                                    img_url +
                                    '<p class="comment-username">' + createName + '</p>' +
                                    '<p class="comment-time">' + day_min_cn + '</p>' +
                                    '<div style="clear: both"></div>' +
                                    '<div class="comment-body">' + html_single + '</div>' +
                                    '<div class="commentFileDiv">' +
                                    '<ul class="commentFileUl" id="file_' + comment.project_task_comment_id + '">' +
                                    '</ul>' +
                                    '</div>' +
                                    '</div>' +
                                    '<div class="clear"></div> ' +
                                    '</div>';

                                for (file in comment.files) {

                                    var arr = comment.files[file].file_name.split(".");
                                    var type = '';
                                    var imgUrl = '';
                                    if (arr[arr.length - 1] == "jpg" || arr[arr.length - 1] == "png" || arr[arr.length - 1] == "jpeg" || arr[arr.length - 1] == "gif" || arr[arr.length - 1] == "bmp" || arr[arr.length - 1] == "psd" || arr[arr.length - 1] == "dwg" || arr[arr.length - 1] == "ico") {
                                        type = "commentPicImg";
                                        imgUrl = '../../images/task/pic.png';
                                    }
                                    else {
                                        type = "commentFileImg";
                                        imgUrl = '../../images/project/word.png';
                                    }

                                    htmlLi += '<li class="commentFileLi" file_data_down = '+comment.files[file].file_url+' file_name_down='+comment.files[file].file_name+'>' +
                                        '<img class="'+type+'" src="'+imgUrl+'"/>' +
                                        '<p class="commentFileName">' + comment.files[file].file_name + '</p>' +
                                        '</li>'
                                }
                            }
                            else {
                                html = '<div class="comment" project_task_comment_id="' + comment.project_task_comment_id + '">' +
                                    '<div class="detailCommentDiv">' +
                                        //'<img class="avatar" src="'+avatar+'" />' +
                                    img_url +
                                    '<p class="comment-username">' + createName + '</p>' +
                                    '<p class="comment-time">' + day_min_cn + '</p>' +
                                    '<div style="clear: both"></div>' +
                                    '<div class="comment-body">' + html_single + '</div>' +
                                    '</div>' +
                                    '<div class="clear"></div> ' +
                                    '</div>';
                            }

                            $("#commentlist").append(html);
                            var ulId = "#file_" + comment.project_task_comment_id;
                            $(ulId).append(htmlLi);

                            //插入新评论
                            if ($(".taskFileLi").length > 0) {
                                $(".taskFileLi").remove();
                                $(".content-div").css("margin-bottom", '8.33vh');
                                comment_file = "";
                            }

                            $(document).on('click','.commentFileLi',function(){
                                $(".call_back_down").show();
                                file_data_down = $(this).attr("file_data_down");
                                file_name_down = $(this).attr("file_name_down");
                            })

                            showAvatar(".user_pic");
                        }
                        else {
                            $(".project-alert").text("Error").show().fadeOut(2000);
                        }
                    }
                },
                error: function (d) {
                    $(".project-alert").text("网络不给力").show().fadeOut(2000);
                }
            })

        }
        else {
            $(".project-alert").text("评论内容不能为空").show().fadeOut(2000);
        }
    });

        //移除内容刷新
        function reloadTaskDetail() {
            window.location.reload();
            //projectTaskDetail();
        }

    //删除项目任务
    function deleteProjectTask(project_task_id,create_id) {
        /*
         project_task_id 项目任务id
         create_id 任务创建者id
         */
        var title = taskDetailUserName+"删除了"+task.project_task_name;
        var url = apiurl+"/projects/task/"+project_task_id+"/delete";
        var urlData = {
            create_id:create_id,
            token:taskDetailToken,
            imtoken:taskDetailImtoken,
            qyxBindId:taskDetailQyxBindId,
            title:title
        }
        $.ajax({
            url:url,
            type:"POST",
            data:urlData,
            beforeSend:function(){
                $(".change-p").text("正在删除任务");
                $(".change-alert").show();
            },
            complete:function(d){
                $(".change-alert").hide();
            },
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if (data.code == 0) {
                        $(".project-alert").text("删除任务成功").show().fadeOut(2000);
                        if (backType == 2) {
                            window.location.href = "../../index.html?htmlType=2";
                        }
                        else if (backType == 0) {
                            window.location.href = "../../index.html?htmlType=0&taskListBack="+taskBackType;
                        }
                        else if (backType == 1) {
                            //返回原生应用
                            quitShare.src = "/quitShare_goBack";
                        } else {
                            if (projectBackType != undefined){
                                window.location.href = "../project/projectDetail.html?project_id="+task_project_id+"&tabbarCount=1&projectCommentBack=1";
                            }else {
                                window.location.href = "../project/projectDetail.html?project_id="+task_project_id+"&tabbarCount=1";
                            }
                        }
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

        //任务评论列表
    function taskCommentList(loadmore){
        if (loadmore != true){
            $("#commentlist").empty();
        }
        var urlData = {
            user_id:taskDetailUserId,
            token:taskDetailToken,
            project_task_status_id:lastCommentId
        }
        $.ajax({
            url: apiurl + "/projects/task/dynamic/"+task.project_task_id,
            type: "GET",
            data:urlData,
            dataType: 'json',
            success: function (d) {
                stop = true;
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if (data.code == 0) {
                        console.log(data);
                        var list = JSON.parse(d).data.projectStatus;
                        commentUserArray = JSON.parse(d).data.userInfos;
                        lastCommentId = list[list.length - 1].id;
                        if (list.length < 10) {
                            stop = false;
                        }
                        for (var i = 0; i < list.length; i++) {
                            var comment = list[i];
                            var html = '';
                            var htmlLi = '';
                            initDate(new Date(comment.create_timestamp));
                            var createName = '';
                            var avatar = '';
                            var qyxBindId = '';
                            for (key in commentUserArray) {
                                if (commentUserArray[key].id == comment.user_id) {
                                    createName = commentUserArray[key].name;
                                    avatar = commentUserArray[key].avatar;
                                    qyxBindId = commentUserArray[key].qyxBindId;
                                }
                            }
                            var img_url;
                            //if (avatar == "") {
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(createName) + "</div>"
                            //} else {
                            if (avatar.length > 0) {
                                var src = avatar_getUrl(taskDetailUserId, taskDetailToken, avatar);
                                img_url += "<img src='" + src + "' class='user_pic' hidden>";
                            }
                            if (comment.status == 0) {
                                var array = comment.comment_body.split('\n');
                                var html_single = "";
                                for(var key in array){
                                    html_single += "<div class='real_content'>"+array[key]+"</div>";
                                }
                                //文字评论
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="detailCommentDiv">' +
                                        //'<img class="avatar" src="'+avatar+'" />' +
                                    img_url +
                                    '<p class="comment-username">' + createName + '</p>' +
                                    '<p class="comment-time">' + day_min_cn + '</p>' +
                                    '<div style="clear: both"></div>' +
                                    '<div class="comment-body">' + html_single + '</div>' +
                                    '</div>' +
                                    '<div class="clear"></div> ' +
                                    '</div>';
                            }
                            else if (comment.status == 1) {
                                var array = comment.comment_body.split('\n');
                                var html_single = "";
                                for(var key in array){
                                    html_single += "<div class='real_content'>"+array[key]+"</div>";
                                }
                                //带文件评论
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="detailCommentDiv">' +
                                        //'<img class="avatar" src="'+avatar+'" />' +
                                    img_url +
                                    '<p class="comment-username">' + createName + '</p>' +
                                    '<p class="comment-time">' + day_min_cn + '</p>' +
                                    '<div style="clear: both"></div>' +
                                    '<div class="comment-body">' + html_single + '</div>' +
                                    '<div class="commentFileDiv">' +
                                    '<ul class="commentFileUl" id="file_' + comment.id + '">' +
                                    '</ul>' +
                                    '</div>' +
                                    '</div>' +
                                    '<div class="clear"></div> ' +
                                    '</div>';

                                for (file in comment.files) {

                                    var arr = comment.files[file].file_name.split(".");
                                    var type = '';
                                    var imgUrl = '';
                                    if (arr[arr.length - 1] == "jpg" || arr[arr.length - 1] == "png" || arr[arr.length - 1] == "jpeg") {
                                        type = "commentPicImg";
                                        imgUrl = '../../images/task/pic.png';
                                    }
                                    else {
                                        type = "commentFileImg";
                                        imgUrl = '../../images/project/word.png';
                                    }

                                    htmlLi += '<li class="commentFileLi" file_data_down = '+comment.files[file].file_url+' file_name_down='+comment.files[file].file_name+'>' +
                                        '<img class="'+type+'" src="'+imgUrl+'"/>' +
                                        '<p class="commentFileName">' + comment.files[file].file_name + '</p>' +
                                        '</li>'
                                }
                            }
                            else if (comment.status == 2) {
                                //创建
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 创建了任务</div>' +
                                    '</div>';
                            }
                            else if (comment.status == 3) {
                                //指派
                                for (key in commentUserArray) {
                                    if (comment.assign_id == commentUserArray[key].id) {
                                        var statusString = "把任务指派给了 " + commentUserArray[key].name;
                                        html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                            '<div class="dynamic">' + day_min_en + ' ' + createName + ' ' + statusString + '</div>' +
                                            '</div>';

                                    }
                                }
                            }
                            else if (comment.status == 4) {
                                //修改
                                //html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                //    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 修改了任务</div>' +
                                //    '</div>';
                                continue;
                            }
                            else if (comment.status == 5) {
                                //删除
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 删除了任务</div>' +
                                    '</div>';
                            }
                            else if (comment.status == 6) {
                                //完成
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 完成了任务</div>' +
                                    '</div>';
                            }
                            else if (comment.status == 7) {
                                //移动
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 移动了任务</div>' +
                                    '</div>';
                            }
                            else if (comment.status == 8) {
                                //撤销完成
                                html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 撤销了任务完成</div>' +
                                    '</div>';
                            }

                            $("#commentlist").append(html);
                            var ulId = "#file_" + comment.id;
                            $(ulId).append(htmlLi);

                            //$(window).unbind('scroll');
                        }

                        $(document).on('click','.commentFileLi',function(){
                            $(".call_back_down").show();
                            file_data_down = $(this).attr("file_data_down");
                            file_name_down = $(this).attr("file_name_down");
                        })

                        showAvatar(".user_pic");
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error: function (d) {
                stop=true;
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //获取项目列表
    function projectLists(user_id) {
        var url = apiurl+"/projects/list";
        var urlData = {
            user_id:user_id,
            group_id:taskDetailGroupId
        }
        $.ajax({
            url:url,
            type:"GET",
            data:urlData,
            success:function(d){
                var comData = d;
                if (d.code == undefined) {
                    comData = JSON.parse(d);
                }
                if (comData.code == 0){
                    var data = JSON.parse(d).data;
                    $(".call_back").hide();
                    //var deHtml = '<div class="title_up_project" projectId="1" projectName="默认项目">'+
                    //    '<div class="le_project">默认项目</div>'+
                    //    '<div class="ri_project">'+
                    //    '<img src="../../../questionnaire/public/img/upper_limit_on.png"></div></div>'
                    //$(".content_big_project").append(deHtml);

                    //var divHeight = data.length * 7.8125 + 7.8125;
                    var divHeight = data.length * 7.8125;
                    var padTop = (100 - divHeight)/2;
                    if (padTop < 20){
                        padTop = 20;
                    }
                    $(".call_back_project").css("paddingTop",padTop+"vh");

                    for(var i=0;i<data.length;i++){
                        var title = data[i].project_title;
                        var projectId = data[i].project_id;
                        var html = '';
                        if (projectId == task_project_id){
                            //当前所属项目
                            html = '<div class="title_up_project" projectId="'+projectId+'" projectName="'+title+'">'+
                                '<div class="le_project">'+title+'</div>'+
                                '<div class="ri_project">'+
                                '<img class="createNewProjectImg" src="../../../questionnaire/public/img/upper_limit_on.png"></div></div>'
                        }
                        else {
                            html = '<div class="title_up_project" projectId="'+projectId+'" projectName="'+title+'">'+
                                '<div class="le_project">'+title+'</div>'+
                                '<div class="ri_project">'+
                                '<img class="createNewProjectImg" src="../../../questionnaire/public/img/upper_limit_off.png"></div></div>'
                        }
                        $(".content_big_project").prepend(html);
                    }

                    $(".call_back_project").show();

                    $('.title_up_project').click(function(){
                        var project_id = $(this).attr("projectId");
                        if (project_id == task_project_id){
                            //当前所属项目
                            $(".project-alert").text("该任务已属于此项目").show().fadeOut(2000);
                        }
                        else {
                            var img = $(this).find("img");
                            $('.ri_project img').attr('src','../../../questionnaire/public/img/upper_limit_off.png');
                            img.attr('src','../../../questionnaire/public/img/upper_limit_on.png');
                            $('.call_back_project').hide();
                            $('.title_up_project').remove();
                            moveTask(project_id);
                        }
                    });
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            }

        })
    }

    //任务详情
    function projectTaskDetail() {
        $(document).on("click",".taskDetail-checkbox",function(){
            if (task.status == 0){
                if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){
                    //调用完成任务
                    completeTask();
                }
                else {
                    $(".project-alert").text("您无权限完成任务").show().fadeOut(2000);
                }
            }
            else if (task.status == 1){
                if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){
                    //调用取消任务
                    revokeTask();
                }
                else {
                    $(".project-alert").text("您无权限撤销完成").show().fadeOut(2000);
                }
            };
        });

        $(document).on("click",".taskDetail-checkring",function(){
            var item_status = $(this).attr("item_status");
            if (item_status == 0 || item_status == "0"){
                //调用完成子项
                if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){
                    //调用完成子项
                    var item_id = $(this).attr("item_id");
                    completeTaskItem(item_id,$(this));
                }
                else {
                    $(".project-alert").text("您无权限完成检查项").show().fadeOut(2000);
                }
            }
            else if (item_status == 1 || item_status == "1"){
                if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){
                    //调用取消子项
                    var item_id = $(this).attr("item_id");
                    revokeTaskItem(item_id,$(this));
                }
                else {
                    $(".project-alert").text("您无权限撤销完成").show().fadeOut(2000);
                }
            };
        });

        var url = apiurl+"/projects/task/"+project_task_id+"";
        var urlData = {
            user_id:taskDetailUserId,
            token:taskDetailToken
        }
        $.ajax({
            url:url,
            type:"GET",
            data:urlData,
            beforeSend:function(d){
                $(".loading").show();
                $(".content-div").hide();
                $("#task-detail-footer").hide();
            },
            complete:function(d){
                $(".loading").hide();
            },
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if (data.code == 0) {
                        task = JSON.parse(d).data;
                        task_project_id = task.project_id;
                        userArray = task.userCallbackString;
                        for (var key in userArray) {
                            if (userArray[key].id == taskDetailUserId) {
                                taskDetailUserName = userArray[key].name;
                            }
                        }
                        var followerCount = 0;
                        if (task.followers.length > 0) {
                            var followers = task.followers.split(",");
                            if (followers[0].length <= 0){
                                followerCount = followers.length - 1;
                            }
                            else {
                                followerCount = followers.length;
                            }
                        }
                        initDate(new Date(task.deadline));

                        var statushtml = '';
                        var classname = '';
                        if (task.status == 0) {
                            statushtml = '<img class="taskDetail-checkbox" src="../../images/task/roundedDisSelected.png" />';
                            classname = '"taskDetail-task-name-uncomplete"';
                        } else {
                            statushtml = '<img class="taskDetail-checkbox" src="../../images/task/roundedSelected.png" />';
                            classname = '"taskDetail-task-name-complete"';
                        }


                        var followhtml = '';

                        var result = $.inArray(taskDetailUserId, followers);
                        if (result == -1) {
                            isFollow = false;
                            followhtml = '<img class="taskDetail-img" id="follow-status" src="../../images/task/attentionImg.png" />';
                        } else {
                            isFollow = true;
                            followhtml = '<img class="taskDetail-img" id="follow-status" src="../../images/task/attentionSelected.png" />';
                        }

                        var responeName = "";
                        for (key in userArray) {
                            if (task.response_id == userArray[key].id) {
                                responeName = userArray[key].name;
                            }
                        }
                        var html = '<div class="first-div">' +
                            '<p class="projectName">项目: ' + task.project_title + '</p>' +
                            '<p class="count">' + followerCount + '人关注</p>' +
                            '<div class="clear"></div>' +
                            '</div>' +
                            '<div class="second-div">' + statushtml +
                            '<p class=' + classname + '>' + task.project_task_name + '</p>' +
                            followhtml +
                            '<p class="finishTask"></p>' +
                            '<div class="clear"></div> ' +
                            '</div>' +
                            '<div class="third-div">' +
                            '<ul class="taskDetail-ul">' +
                            '<li class="taskDetail-li" id = "choosePrincipalLi">' +
                            '<p class="taskDetail-p" id="principal">' + responeName + ' 负责</p>' +
                            '<img class="taskDetail-Rimg" src="../../images/task/arrowRightImg.png" />' +
                            '<hr class="bottomLine" />' +
                            '</li>' +
                            '<li class="taskDetail-li">' +
                            '<input class="newTask-input" id="deadline" type="text" readonly="readonly" value="' + year_mon_day_cn + ' 到期"  placeholder="设置截止时间" />' +
                            '<img class="taskDetail-Rimg" src="../../images/task/arrowRightImg.png" />' +
                            '</li>' +
                            '</ul>' +
                            '<div class="fourth-div">' +
                            '<div id="checklist"></div>' +
                            '<div class="clear"></div> ' +
                            '<div class="inputContainer">' +
                            '<img class="addItemImg" src="../../images/project/addImg.png" />' +
                            '<input class="taskDetail-input" placeholder="添加检查项" maxlength="40">' +
                            '</div>' +
                            '<div class="buttonContainer">' +
                            '<button id="add" >添加</button>' +
                            '<button id="cancel" >取消</button>' +
                            '</div>' +
                            '</div>' +
                            '<div class="clear"></div> ' +
                            '</div>';

                        $(document).on('click', '#choosePrincipalLi', function () {
                            if (taskDetailUserId == task.create_id) {
                                $("#addMemberDiv").show();
                                $(".taskDetail-container").hide();
                                //获取项目详情
                                projectDetail(task_project_id);
                            }
                            else {
                                $(".project-alert").text("您无权限修改负责人").show().fadeOut(2000);
                            }
                        });

                        $(document).on('click', '#follow-status', function () {
                            if (isFollow == false) {
                                //关注此任务
                                followerTask(1);
                            }
                            else {
                                followerTask(0);
                            }
                        });

                        var createName = "";
                        for (key in userArray) {
                            if (task.create_id == userArray[key].id) {
                                createName = userArray[key].name;
                            }
                        }
                        initDate(new Date(task.create_timestamp));
                        //html += '<p class="dynamic">' + day_min_en + ' ' + createName + ' 创建了任务</p>' +
                        //    '<div id="commentlist" class="commentlist"></div>';
                        html += '<div id="commentlist" class="commentlist"></div>';
                        $("#task-detail").empty().append(html);

                        $(".content-div").show();
                        $("#task-detail-footer").show();

                        if (task.status == 0) {
                            $(".finishTask").hide();
                        } else {
                            initDate(new Date(task.complete_timestamp));
                            var finishName = "";
                            for (key in userArray) {
                                if (task.completer_id == userArray[key].id) {
                                    finishName = userArray[key].name;
                                }
                            }
                            $(".finishTask").text("(" + finishName + " " + mon_day_en + " " + hours_min + " 完成任务)").show();
                        }

                        //绑时间控件
                        if (taskDetailUserId == task.create_id){
                            selectDate($(".newTask-input"));
                        }
                        else {
                            $(document).on('click', '.newTask-input', function () {
                                $(".project-alert").text("您无权限修改时间").show().fadeOut(2000);
                            });
                        }
                        //加载评论
                        $("#commentlist").empty();
                        configCommentList(task.comments);

                        //添加检查项
                        var items = task.items;
                        var itemshtml = '';
                        for (var i = 0; i < items.length; i++) {
                            var item = items[i];

                            var rowString = 'itemRow_'+i;
                            var itemstatushtml = '';
                            var itemclassname = '';
                            if (item.status == 0) {
                                itemstatushtml = '<div class="item_detail_'+i+'"><img class="taskDetail-checkring" item_id="' + item.project_task_item_id + '" item_status="' + item.status + '" src="../../images/task/circleCheckBoxUnselect.png" />';
                                itemclassname = '"taskDetail-task-name-uncomplete"';

                                var rows = 2;
                                if (item.project_task_item_title.length > 32) {
                                    rows = 3;
                                }

                                itemshtml += '<div class="second-div '+rowString+'">' + itemstatushtml +
                                    '<textarea class=' + itemclassname + ' itemRow="'+i+'" maxlength="40" placeholder="添加检查项" text_itemId = "' + item.project_task_item_id + '" rows="'+rows+'">' + item.project_task_item_title + '</textarea>' +
                                    '<div class="taskDetail-deleteItem" item_id="' + item.project_task_item_id + '">' +
                                    '<img style="width: 50%;height: 50%;float: left;margin-left: 25%;margin-top: 25%;" src="../../images/task/delete.png" /></div></div>' +
                                    '<hr class="bottomLine" />' +
                                    '</div>';
                            } else {
                                itemstatushtml = '<img class="taskDetail-checkring" item_id="' + item.project_task_item_id + '" item_status="' + item.status + '" src="../../images/task/circleCheckBoxSelect.png" />';
                                itemclassname = '"taskDetail-task-name-complete"';

                                itemshtml += '<div class="second-div '+rowString+'">' + itemstatushtml +
                                    '<p class=' + itemclassname + '>' + item.project_task_item_title + '</p>' +
                                    '<div class="taskDetail-deleteItem" item_id="' + item.project_task_item_id + '">' +
                                    '<img style="width: 50%;height: 50%;float: left;margin-left: 25%;margin-top: 25%;" src="../../images/task/delete.png" /></div></div>' +
                                    '<hr class="bottomLine" />' +
                                    '</div>';
                            }



                        }
                        $("#checklist").append(itemshtml);


                        $(document).on('click', ".taskDetail-deleteItem", function() {
                            if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){
                                deleteItemId = $(this).attr("item_id");
                                $(".title_big").text("确认删除此检查项?");
                                $(".call_back_dele").show();
                            }
                            else {
                                $(".project-alert").text("您无权限删除检查项").show().fadeOut(2000);
                                $(".taskDetail-input").blur();
                            }
                        });

                        $(document).on('focus', '.taskDetail-input', function () {
                            if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){
                                $(".buttonContainer").show();

                                var documentHeight = $(".loading-div").outerHeight(true);  //整个html高度
                                var windownHeight = $(window).height();  //屏幕高度
                                var divHeight = $(".first-div").outerHeight(true) + $(".second-div").outerHeight(true) + $(".third-div").outerHeight(true); //键盘升起需要高于键盘的div总高度
                                var keyboardHeight = windownHeight/2 + $(".task-bottom-comment-box").outerHeight(true);  //半屏
                                var scrollHeight = divHeight + keyboardHeight - windownHeight;

                                if (divHeight > windownHeight/2){
                                    //需要滑动
                                    var canScrollHeight = documentHeight - windownHeight;
                                    if (canScrollHeight < scrollHeight) {
                                        //滑动距离不够
                                        var moreheight = (scrollHeight - canScrollHeight)/windownHeight * 100 + 'vh' ;
                                        $(".loading-div").append('<div class="moreDiv" style="width: 100%;height: '+moreheight+'"></div>');
                                    }

                                    window.scrollTo(0,scrollHeight);
                                }
                            }
                            else {
                                $(".project-alert").text("您无权限添加检查项").show().fadeOut(2000);
                                $(".taskDetail-input").blur();
                            }
                        });

                        $(document).on('focus', '.taskDetail-task-name-uncomplete', function () {
                            $(".changeButtonContainer").remove();

                            if (taskDetailUserId == task.create_id || taskDetailUserId == task.response_id){

                                var item_id = $(this).attr("text_itemId");

                                var textStr = $(this).val();

                                var html = '<div class="changeButtonContainer">' +
                                             '<button class="changeAdd" item_id = "'+item_id+'" textString = "'+textStr+'">修改</button>' +
                                             '<button class="changeCancel" item_id = "'+item_id+'" textString = "'+textStr+'">取消</button>' +
                                           '</div>'
                                var row = $(this).attr('itemRow');
                                var rowString = '.item_detail_'+ row;

                                $(rowString).append(html);

                                var divHeight = $(".first-div").outerHeight(true) + $(".second-div").outerHeight(true) + $(".taskDetail-ul").outerHeight(true); //键盘升起需要高于键盘的div总高度
                                for (var i = 0; i <= row; i++) {
                                    var rowStr = '.itemRow_'+ i;
                                    divHeight += $(rowStr).outerHeight(true);
                                }

                                var documentHeight = $(".loading-div").outerHeight(true);  //整个html高度
                                var windownHeight = $(window).height();  //屏幕高度
                                var keyboardHeight = windownHeight/2 + $(".task-bottom-comment-box").outerHeight(true);  //半屏
                                var scrollHeight = divHeight + keyboardHeight - windownHeight;

                                if (divHeight > windownHeight/2){
                                    //需要滑动
                                    var canScrollHeight = documentHeight - windownHeight;
                                    if (canScrollHeight < scrollHeight) {
                                        //滑动距离不够
                                        var moreheight = (scrollHeight - canScrollHeight)/windownHeight * 100 + 'vh' ;
                                        $(".loading-div").append('<div class="moreDiv" style="width: 100%;height: '+moreheight+'"></div>');
                                    }

                                    window.scrollTo(0,scrollHeight);
                                }

                                $(document).on('click', '.changeAdd', function () {

                                    var  item_id = $(this).attr("item_id");
                                    var itemTitle = $.trim($(".taskDetail-task-name-uncomplete[text_itemId='"+item_id+"']").val());
                                    if (itemTitle == "") {
                                        $(".project-alert").text("检查项内容不能为空").show().fadeOut(2000);
                                        $(".taskDetail-task-name-uncomplete[text_itemId='"+item_id+"']").val($(this).attr("textString"));
                                    } else {
                                        changeProjectTaskItem(item_id,$(".taskDetail-task-name-uncomplete[text_itemId='"+item_id+"']").val());
                                    }
                                    $(".changeButtonContainer").remove();
                                });

                                $(document).on('click', '.changeCancel', function () {
                                    $(".changeButtonContainer").remove();
                                    var  item_id = $(this).attr("item_id");
                                    $(".taskDetail-task-name-uncomplete[text_itemId='"+item_id+"']").val($(this).attr("textString"));
                                });
                            }
                            else {
                                $(".project-alert").text("您无权限修改检查项").show().fadeOut(2000);
                                $(".taskDetail-task-name-uncomplete").blur();
                            }
                        });

                        $(document).on('click', '#add', function () {
                            $(".moreDiv").remove();

                            var itemVal = HTMLEncode($(".taskDetail-input").val());
                            var itemTitle = $.trim(itemVal);
                            if (itemTitle == "") {
                                $(".project-alert").text("检查项内容不能为空").show().fadeOut(2000);
                            } else {
                                createProjectTaskItem(project_task_id, itemTitle);
                            }
                        });

                        $(document).on('click', '#cancel', function () {
                            $(".moreDiv").remove();

                            $(".taskDetail-input").val("");
                            //$(".taskDetail-input").blur();
                            $(".buttonContainer").hide();
                        });

                        //限制字数
                        $(".taskDetail-input").bind("input propertychange",function(){
                            var nameStr = $(this).val();
                            if(nameStr.length >= 40){
                                $(".project-alert").text("检查项名最多40字").show().fadeOut(2000);
                            }
                        });

                        $(".taskDetail-task-name-uncomplete").bind("input propertychange",function(){
                            var nameStr = $(this).val();
                            if(nameStr.length >= 40){
                                $(".project-alert").text("检查项名最多40字").show().fadeOut(2000);
                            }
                        });

                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }

            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

        //布局评论列表
        function configCommentList(commentList) {
            stop = true;
            //debugger;
            var list = commentList.projectStatus;
            commentUserArray = commentList.userInfos;
            lastCommentId = list[list.length - 1].id;
            if (list.length < 10) {
                stop = false;
            }
            for (var i = 0; i < list.length; i++) {
                var comment = list[i];
                var html = '';
                var htmlLi = '';
                initDate(new Date(comment.create_timestamp));
                var createName = '';
                var avatar = '';
                var qyxBindId = '';
                for (key in commentUserArray) {
                    if (commentUserArray[key].id == comment.user_id) {
                        createName = commentUserArray[key].name;
                        avatar = commentUserArray[key].avatar;
                        qyxBindId = commentUserArray[key].qyxBindId;
                    }
                }
                var img_url;
                //if (avatar == "") {
                    var color = avatar_getColor(qyxBindId);
                    img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(createName) + "</div>"
                //} else {
                if (avatar.length > 0) {
                    var src = avatar_getUrl(taskDetailUserId, taskDetailToken, avatar);
                    img_url += "<img src='" + src + "' class='user_pic' hidden>";
                }
                if (comment.status == 0) {
                    var array = comment.comment_body.split('\n');
                    var html_single = "";
                    for(var key in array){
                        html_single += "<div class='real_content'>"+array[key]+"</div>";
                    }
                    //文字评论
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="detailCommentDiv">' +
                            //'<img class="avatar" src="'+avatar+'" />' +
                        img_url +
                        '<p class="comment-username">' + createName + '</p>' +
                        '<p class="comment-time">' + day_min_cn + '</p>' +
                        '<div style="clear: both"></div>' +
                        '<div class="comment-body">' + html_single + '</div>' +
                        '</div>' +
                        '<div class="clear"></div> ' +
                        '</div>';
                }
                else if (comment.status == 1) {
                    var array = comment.comment_body.split('\n');
                    var html_single = "";
                    for(var key in array){
                        html_single += "<div class='real_content'>"+array[key]+"</div>";
                    }
                    //带文件评论
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="detailCommentDiv">' +
                            //'<img class="avatar" src="'+avatar+'" />' +
                        img_url +
                        '<p class="comment-username">' + createName + '</p>' +
                        '<p class="comment-time">' + day_min_cn + '</p>' +
                        '<div style="clear: both"></div>' +
                        '<div class="comment-body">' + html_single + '</div>' +
                        '<div class="commentFileDiv">' +
                        '<ul class="commentFileUl" id="file_' + comment.id + '">' +
                        '</ul>' +
                        '</div>' +
                        '</div>' +
                        '<div class="clear"></div> ' +
                        '</div>';

                    for (file in comment.files) {

                        var arr = comment.files[file].file_name.split(".");
                        var type = '';
                        var imgUrl = '';
                        if (arr[arr.length - 1] == "jpg" || arr[arr.length - 1] == "png" || arr[arr.length - 1] == "jpeg") {
                            type = "commentPicImg";
                            imgUrl = '../../images/task/pic.png';
                        }
                        else {
                            type = "commentFileImg";
                            imgUrl = '../../images/project/word.png';
                        }

                        htmlLi += '<li class="commentFileLi" file_data_down = '+comment.files[file].file_url+' file_name_down='+comment.files[file].file_name+'>' +
                            '<img class="'+type+'" src="'+imgUrl+'"/>' +
                            '<p class="commentFileName">' + comment.files[file].file_name + '</p>' +
                            '</li>'
                    }
                }
                else if (comment.status == 2) {
                    //创建
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="dynamic">' + day_min_en + ' ' + createName + ' 创建了任务</div>' +
                        '</div>';
                }
                else if (comment.status == 3) {
                    //指派
                    for (key in commentUserArray) {
                        if (comment.assign_id == commentUserArray[key].id) {
                            var statusString = "把任务指派给了 " + commentUserArray[key].name;
                            html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                                '<div class="dynamic">' + day_min_en + ' ' + createName + ' ' + statusString + '</div>' +
                                '</div>';

                        }
                    }
                }
                else if (comment.status == 4) {
                    //修改
                    //html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                    //    '<div class="dynamic">' + day_min_en + ' ' + createName + ' 修改了任务</div>' +
                    //    '</div>';
                    continue;
                }
                else if (comment.status == 5) {
                    //删除
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="dynamic">' + day_min_en + ' ' + createName + ' 删除了任务</div>' +
                        '</div>';
                }
                else if (comment.status == 6) {
                    //完成
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="dynamic">' + day_min_en + ' ' + createName + ' 完成了任务</div>' +
                        '</div>';
                }
                else if (comment.status == 7) {
                    //移动
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="dynamic">' + day_min_en + ' ' + createName + ' 移动了任务</div>' +
                        '</div>';
                }
                else if (comment.status == 8) {
                    //撤销完成
                    html = '<div class="comment" project_task_comment_id="' + comment.id + '">' +
                        '<div class="dynamic">' + day_min_en + ' ' + createName + ' 撤销了任务完成</div>' +
                        '</div>';
                }

                $("#commentlist").append(html);
                var ulId = "#file_" + comment.id;
                $(ulId).append(htmlLi);
            }

            $(document).on('click','.commentFileLi',function(){
                $(".call_back_down").show();
                file_data_down = $(this).attr("file_data_down");
                file_name_down = $(this).attr("file_name_down");
            });
            showAvatar(".user_pic");
        }

        //获取项目详情
        function projectDetail(project_id) {
            var url = apiurl+"/projects/"+project_id+"";
            var urlData = {
                user_id:taskDetailUserId,
                token:taskDetailToken
            }
            $.ajax({
                url:url,
                type:"GET",
                data:urlData,
                beforeSend:function(d){
                    $(".memberloading").show();
                },
                complete:function(d){
                    $(".memberloading").hide();
                },
                success:function(d){
                    if (d.msg == 202){
                        $(".token_iframe").show();
                    }
                    else {
                        var data = d;
                        if (d.code == undefined) {
                            data = JSON.parse(d);
                        }
                        if (data.code == 0) {
                            var data = JSON.parse(d).data;
                            userArray = data.userCallbackString;
                            for (key in userArray) {
                                var img_url;
                                //if (userArray[key].avatar == "") {
                                    var color = avatar_getColor(userArray[key].qyxBindId);
                                    img_url = "<div class='user_pic_div_se' style='background-color: " + color + "'>" + avatar_name(userArray[key].name) + "</div>"
                                //} else {
                                if (userArray[key].avatar.length > 0) {
                                    var src = avatar_getUrl(taskDetailUserId, taskDetailToken, userArray[key].avatar);
                                    img_url += "<img src='" + src + "' class='user_pic_se' hidden>";
                                }
                                var html = '';
                                if (userArray[key].id == task.response_id) {
                                    //当前负责人
                                    selectPrincipal = userArray[key].id;
                                    html = '<li class="member-li" userId="' + userArray[key].id + '">' +
                                        '<div class="addDiv"></div> '+
                                        img_url +
                                        '<p class="nameP">' + userArray[key].name + '</p>' +
                                        '<div class="user_right"><img class="select_principal_img" src="../../../log/logImg/tick.png" /></div> '+
                                        '</li>'
                                }
                                else {
                                    html = '<li class="member-li" userId="' + userArray[key].id + '">' +
                                        '<div class="addDiv"></div> '+
                                        img_url +
                                        '<p class="nameP">' + userArray[key].name + '</p>' +
                                        '</li>'
                                }
                                $(".member-ul").append(html);
                            }
                            $(".member-li").on("click",function(){
                                    //选择负责人
                                selectPrincipal = $(this).attr("userId");
                                if (selectPrincipal == task.response_id){
                                    $("#addMemberDiv").hide();
                                    $(".taskDetail-container").show();
                                    $(".member-li").remove();
                                    selectPrincipal = '';
                                    $(".project-alert").text("该任务已是此人负责").show().fadeOut(2000);
                                }
                                else {
                                    changeResponse(selectPrincipal);
                                }
                            });

                            showAvatar(".user_pic_se");
                        }
                        else {
                            $(".project-alert").text("Error").show().fadeOut(2000);
                        }
                    }
                },
                error:function(d){
                    $(".project-alert").text("网络不给力").show().fadeOut(2000);
                }
            })
        }

    //时间控件方法
    function selectDate(obj) {
        var currYear = (new Date()).getFullYear();
        var opt = {};
        opt.date = { preset: 'date' };
        opt.datetime = { preset: 'datetime' };
        opt.time = { preset: 'time' };
        opt.default = {
            theme: 'sense-ui', //皮肤样式
            display: 'modal', //显示方式
            mode: 'scroller', //日期选择模式
            lang: 'zh',
            dateFormat: 'yyyy-mm-dd',
            startYear: currYear - 10, //开始年份
            endYear: currYear + 10, //结束年份
            minDate: new Date(),
            onSelect:function(){
                var timeString = $("#deadline").val();
                var year = timeString.substr(0,4);
                var mon = timeString.substr(5,2);
                var day = timeString.substr(8,2);
                var date = year+"年"+mon+"月"+day+"日 到期";
                initTimestamp(timeString);
                $("#deadline").val(date);
                changeEndtime(changeTimestamp);
            }
        };
        var optDateTime = $.extend(opt['datetime'], opt['default']);
        obj.mobiscroll(optDateTime).date(optDateTime);
    }

    //时间转换时间戳
    function initTimestamp(date){
        var time = date;
        time = new Date(Date.parse(new Date(date)));
        changeTimestamp = time.getTime();
    }


    //完成任务
    function completeTask() {
        var data={
            project_task_id:task.project_task_id,
            user_id:taskDetailUserId,
            complete_timestamp:new Date().getTime(),
            token:taskDetailToken,
            imtoken:taskDetailImtoken,
            qyxBindId:taskDetailQyxBindId,
            title:taskDetailUserName+"完成了"+task.project_task_name
        };
        $.ajax({
            url: apiurl + "/projects/task/complete",
            type: "PUT",
            dataType: 'json',
            data:data,
            header:{
                "content-type": "application/x-www-form-urlencoded"
            },
            beforeSend:function(){
                $(".change-p").text("数据加载中...");
                $(".change-alert").show();
            },
            complete:function(d){
                $(".change-alert").hide();
            },
            success: function (d) {
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if (data.code == 0){
                        var data = JSON.parse(d).data;
                        reloadTaskDetail();
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }

            },
            error: function (d) {
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //完成项目子任务
    function completeTaskItem(project_task_item_id,checkbox) {
        var data={
            project_task_item_id:project_task_item_id,
            complete_timestamp:new Date().getTime()
        };
        $.ajax({
            url: apiurl + "/projects/task/item/complete",
            type: "PUT",
            dataType: 'json',
            data:data,
            header:{
                "content-type": "application/x-www-form-urlencoded"
            },
            beforeSend:function(){
                $(".change-p").text("数据加载中...");
                $(".change-alert").show();
            },
            complete:function(d){
                $(".change-alert").hide();
            },
            success: function (d) {
                var completeData = d;
                if (d.code == undefined) {
                    completeData = JSON.parse(d);
                }
                if (completeData.code == 0){
                    var data = JSON.parse(d).data;
                    reloadTaskDetail();
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }

            },
            error: function (d) {
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

        //取消完成任务
        function revokeTask() {
            var data={
                project_task_id:task.project_task_id,
                user_id:taskDetailUserId,
                complete_timestamp:new Date().getTime(),
                token:taskDetailToken,
                imtoken:taskDetailImtoken,
                qyxBindId:taskDetailQyxBindId,
                title:taskDetailUserName+"取消了"+task.project_task_name+"的完成"
            };
            $.ajax({
                url: apiurl + "/projects/task/revoke",
                type: "PUT",
                dataType: 'json',
                data:data,
                header:{
                    "content-type": "application/x-www-form-urlencoded"
                },
                beforeSend:function(){
                    $(".change-p").text("数据加载中...");
                    $(".change-alert").show();
                },
                complete:function(d){
                    $(".change-alert").hide();
                },
                success: function (d) {
                    if (d.msg == 202){
                        $(".token_iframe").show();
                    }
                    else {
                        var data = d;
                        if (d.code == undefined) {
                            data = JSON.parse(d);
                        }
                        if (data.code == 0){
                            reloadTaskDetail();
                        }
                        else {
                            $(".project-alert").text("Error").show().fadeOut(2000);
                        }
                    }

                },
                error: function (d) {
                    $(".project-alert").text("网络不给力").show().fadeOut(2000);
                }
            })
        }

        //取消完成项目子任务
        function revokeTaskItem(project_task_item_id,checkbox) {
            var data={
                project_task_item_id:project_task_item_id,
                complete_timestamp:new Date().getTime()
            };
            $.ajax({
                url: apiurl + "/projects/task/item/revoke",
                type: "PUT",
                dataType: 'json',
                data:data,
                header:{
                    "content-type": "application/x-www-form-urlencoded"
                },
                beforeSend:function(){
                    $(".change-p").text("数据加载中...");
                    $(".change-alert").show();
                },
                complete:function(d){
                    $(".change-alert").hide();
                },
                success: function (d) {
                    var completeData = d;
                    if (d.code == undefined) {
                        completeData = JSON.parse(d);
                    }
                    if (completeData.code == 0){
                        reloadTaskDetail();
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }

                },
                error: function (d) {
                    $(".project-alert").text("网络不给力").show().fadeOut(2000);
                }
            })
        }
    //创建项目任务子任务(检查项)
    function createProjectTaskItem(project_task_id,project_task_item_title) {
        //project_task_item_title 子任务标题
        var url = apiurl+"/projects/task/item";
        var data = {
            project_task_id:project_task_id,
            project_task_item_title:project_task_item_title
        }
        $.ajax({
            url:url,
            type:"POST",
            data:data,
            beforeSend:function(d){
                $(".change-p").text("正在创建检查项");
                $(".change-alert").show();
            },
            complete:function(d){
                $(".change-alert").hide();
            },
            success:function(d){
                $(".taskDetail-input").val("");
                $(".buttonContainer").hide();
                var data = d;
                if (d.code == undefined) {
                    data = JSON.parse(d);
                }
                if(data.code == 0){
                    $(".project-alert").text("创建检查项成功").show().fadeOut(2000);
                    reloadTaskDetail();
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

        //修改检查项
        function changeProjectTaskItem(project_task_id,project_task_item_title) {
            var url = apiurl+"/projects/task/item/"+project_task_id+"";
            var data = {
                projectTaskItemTitle:project_task_item_title
            }

            $.ajax({
                url:url,
                type:"POST",
                data:data,
                beforeSend:function(d){
                    $(".change-p").text("正在修改检查项");
                    $(".change-alert").show();
                },
                complete:function(d){
                    $(".change-alert").hide();
                },
                success:function(d){
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if(data.code == 0){
                        $(".project-alert").text("修改检查项成功").show().fadeOut(2000);
                    }
                    else {
                        $(".project-alert").text("修改检查项失败").show().fadeOut(2000);
                    }
                    window.location.reload();
                },
                error:function(d){
                    $(".project-alert").text("网络不给力").show().fadeOut(2000);
                }
            })
        }

    //取消 添加关注 0取消  1关注
    function followerTask (type) {
        var url = apiurl+"/projects/task/followers";
        //var url = "http://172.20.10.11:8080/WorkAssistant/api/v1/projects/task/followers"
        var data = {
            project_task_id:task.project_task_id,
            user_id:taskDetailUserId,
            type:type
        }
        $.ajax({
            url:url,
            type:"PUT",
            data:data,
            success:function(d){
                var data = d;
                if (d.code == undefined) {
                    data = JSON.parse(d);
                }
                if(data.code == 0){
                    reloadTaskDetail();
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //任务修改负责人
    function changeResponse (response_id){
        var url = apiurl+"/projects/task/response";
        var data = {
            project_task_id:task.project_task_id,
            response_id:response_id,
            user_id:taskDetailUserId,
            token:taskDetailToken,
            imtoken:taskDetailImtoken,
            qyxBindId:taskDetailQyxBindId,
            title:taskDetailUserName+"重新指派了"+task.project_task_name+"的负责人"
        }
        $.ajax({
            url:url,
            type:"PUT",
            data:data,
            beforeSend:function(){
                $(".memberchange-p").text("正在修改负责人");
                $(".memberchange-alert").show();
            },
            complete:function(){
                $(".change-alert").hide();
            },
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if(data.code == 0){
                        $(".project-alert").text("修改负责人成功").show().fadeOut(2000);
                        $("#addMemberDiv").hide();
                        $(".taskDetail-container").show();
                        $(".member-li").remove();
                        selectPrincipal = '';
                        reloadTaskDetail();
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //任务修改截止时间
    function changeEndtime (deadline){
        var url = apiurl+"/projects/task/deadline";
        var data = {
            project_task_id:task.project_task_id,
            deadline:deadline,
            user_id:taskDetailUserId,
            token:taskDetailToken,
            imtoken:taskDetailImtoken,
            qyxBindId:taskDetailQyxBindId,
            title:taskDetailUserName+"修改了"+task.project_task_name+"的截止时间"
        }
        $.ajax({
            url:url,
            type:"PUT",
            data:data,
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                        data = JSON.parse(d);
                    }
                    if(data.code == 0){
                        $(".project-alert").text("修改截止时间成功").show().fadeOut(2000);
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);

                    }
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //移动任务
    function moveTask (project_id){
        var url = apiurl+"/projects/task/move";
        var data = {
            project_task_id:task.project_task_id,
            project_id:project_id,
            user_id:taskDetailUserId,
            token:taskDetailToken,
            imtoken:taskDetailImtoken,
            qyxBindId:taskDetailQyxBindId,
            title:taskDetailUserName+"移动了"+task.project_task_name
        }
        $.ajax({
            url:url,
            type:"PUT",
            data:data,
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var data = d;
                    if (d.code == undefined) {
                       data = JSON.parse(d);
                    }
                    if(data.code == 0){
                        $(".project-alert").text("移动任务成功").show().fadeOut(2000);
                        reloadTaskDetail();
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }
        //评论框键盘收起
        function packupKeyboard() {
            $("#task-detail-footer").css("bottom",'0vh');
            $(".task-comment-box-real").blur();
        }
   })

    //删除项目任务子任务
    function deleteTaskItem(project_task_Item_id) {

        var url = apiurl+"/projects/task/item/"+project_task_Item_id+"";
        $.ajax({
            url:url,
            type:"DELETE",
            beforeSend:function(){
                $(".change-p").text("正在删除检查项");
                $(".change-alert").show();
            },
            success:function(d){
                $(".change-alert").hide();
                var data = d;
                if (d.code == undefined) {
                    data = JSON.parse(d);
                }
                if (data.code == 0) {
                    $(".project-alert").text("删除检查项成功").show().fadeOut(2000);
                    window.location.reload();
                }
                else {
                    $(".project-alert").text("删除检查项失败").show().fadeOut(2000);
                }

            },
            error:function(d){
                $(".change-alert").hide();
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }
})(jQuery);
